package com.css.datasourceSwitch;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

/**
 * @author liusl
 * @description:
 * @date 2024/9/12 下午4:10
 */
@Service
public class DataSourceService {
    @Autowired
    private DynamicRoutingDataSource dynamicRoutingDataSource;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 模拟从数据库获取数据源配置
//    private DataSourceProperties getDataSourcePropertiesFromDB(String province) {
//        // 从数据库中查询省份对应的数据源信息，返回 DataSourceProperties 对象
//        // 假设这里是从数据库查询到的配置信息
//        DataSourceProperties properties = new DataSourceProperties();
//        properties.setUrl("jdbc:kingbase8://39.106.153.7:54321/dzyjzhjspt_proper_anhui");
//        properties.setUsername("system");
//        properties.setPassword("system");
//        properties.setDriverClassName("com.kingbase8.Driver");
//        return properties;
//    }

// 在应用启动时加载所有省份数据源
    @PostConstruct
    public void initDatasouceFromDB(){
        loadProvinceDataSources();
    }

    public void loadProvinceDataSources() {
        // 查询数据库中存储的所有省份数据源信息
        String sql = "SELECT id,name,url,username,password,dept_id FROM data_source_config where deleted = 0";
        List<Map<String, Object>> provinceDataSources = jdbcTemplate.queryForList(sql);

        for(Map<String, Object> e:provinceDataSources){
            String province = "province_"+e.get("dept_id");

            DataSourceProperty dataSourceProperty = new DataSourceProperty();
            dataSourceProperty.setUrl((String) e.get("url"));
            dataSourceProperty.setUsername((String) e.get("username"));
            dataSourceProperty.setPassword((String) e.get("password"));
            dataSourceProperty.setDriverClassName("com.kingbase8.Driver");

            // 使用 HikariDataSource 构建新的数据源
            HikariDataSource dataSource = new HikariDataSource();
            dataSource.setJdbcUrl(dataSourceProperty.getUrl());
            dataSource.setUsername(dataSourceProperty.getUsername());
            dataSource.setPassword(dataSourceProperty.getPassword());
            dataSource.setDriverClassName(dataSourceProperty.getDriverClassName());

            // 动态添加数据源
            dynamicRoutingDataSource.addDataSource(province, dataSource);
        }
    }
}
